# coding: utf-8


import socket
import json

from topapi import *

def newuser(nick, top_session): 
    sock = socket.socket()
    sock.settimeout(0.5)
    sock.connect(('127.0.0.1', 8300))
    new_user_data = {'top_session':top_session, 'nick':nick}
    new_user_data = json.dumps(new_user_data)
    sock.send(new_user_data+'\n\n')
    res = sock.recv(128)
    sock.close()
    if 'success' not in res:
        raise Exception('recv from new user[%s] server: %s' %(nick, res))


def check_new_user(mdb, nick, top_session):
    #is user of baby say:
    u = mdb.say_user.find_one({'_id':nick})
    if u:
        return
    userobj = User()
    tu = userobj.get(top_session, nick)
    tu = tu['user']
    tu['_id'] = tu['nick']
    mdb.say_user.save(tu)
    #is user of taogold?
    u = mdb.user.find_one({'_id':nick})
    if u:
        #not need to get items etc. from taobao
        return
    #get items etc. from taobao
    newuser(nick, top_session)


